#!/bin/bash
#author zhangbolin10@crc.com.hk
#Version: 1.0
#describe: A custom script for nginx start || stop || check
#ARGS:
#   check  Check nginx process
#   start   Start nginx with configure file
#   stop    Stop nginx
#######################
#error code
#   1   null VIP
#   2   NGINX down
#   3   NGINX can not stop
#   4   no NGINX BIN
#   5   no NGINX CONFIG
#   6   nginx configfile error
#   100 unknow result
#########################

#nginx 执行文件路径
NGINX_BIN="$(which nginx)"
#nginx 配置文件路径
NGINX_CONF="/etc/nginx/nginx.conf"
#检测VIP,暂时只支持一个
NGINX_VIP="192.168.33.16"
#keepalived 配置文件位置
KEEPALIVED_CONF="/etc/keepalived/keepalived.conf"
#start 脚本等待时间
START_WAIT_TIME=1
#stop 脚本等待时间
STOP_WAIT_TIME=3
#结果默认值，不要修改
RESULT=100
#获取程序名
PROG_NAME=$0

#定义日志

#检测nginx可执行文件是否存在
if [ -z "$NGINX_BIN" ]; then RESULT=4; fi
#检测配置文件是否存在
if [ ! -s "$NGINX_CONF" ]; then RESULT=5; fi

#获取keepalived 配置文件中的vip 暂时不用到此函数
function getVIP() {
    awk 'BEGIN{STATUS="STOP"}{if (match($0,/}/)){STATUS="STOP"};if (STATUS=="RECORD"){print $0};if (match($0,/virtual_ipaddress/)){STATUS="RECORD"}}' \
        KEEPALIVED_CONF
    return 0
}
#检查是否VIP是否在此主机上
function checkVIP() {
    if [ -z "$(ip addr | grep $NGINX_VIP)" ]; then
        return 1
    else
        return 0
    fi
}
#检查nginx进行是否存在
function checkNginx() {
    if [ 0 -eq $(ps -C nginx --no-headers | wc -l) ]; then
        return 2
    else
        return 0
    fi
}

function check() {
    checkVIP && checkNginx
    return $?
}

function start() {
    if checkNginx; then
        $NGINX_BIN -t
    else
        if checkVIP; then
            if $NGINX_BIN -t; then
                $NGINX_BIN -c "$NGINX_CONF"
            else
                return 6
            fi
        else
            return 1
        fi
    fi
    sleep $START_WAIT_TIME
    return $(checkNginx)
}

function stop() {
    if checkNginx; then
        $NGINX_BIN -s stop
    fi
    sleep $STOP_WAIT_TIME
    if checkNginx; then
        return 3
    else
        return 0
    fi
}

case $1 in
"check")
    echo "checking nginx"
    check
    ;;
"start")
    echo "starting nginx"
    start
    ;;
"stop")
    echo "stopping nginx"
    stop
    ;;
"")
    $NGINX_BIN -v
    ;;
*)
    $NGINX_BIN $@
    ;;
esac
#获取执行结果并输出
RESULT=$?

case $RESULT in
0)
    echo "OK"
    ;;
1)
    echo "null VIP"
    ;;
2)
    echo "NGINX down"
    ;;
3)
    echo "NGINX can not stop"
    ;;
4)
    echo "no NGINX BIN"
    ;;
5)
    echo "no NGINX CONFIG"
    ;;
6)
    echo "nginx configfile error"
    ;;
100)
    echo "unknow result"
    ;;
esac
exit $RESULT
